package com.vmix.vmixmobiledemo;





import com.vmix.android.vmixsdk.rds.FileUploadService;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.content.ServiceConnection;
import android.content.ComponentName;
import android.content.IntentFilter;
import android.os.IBinder;




public class UploadActivity extends Activity {
	
	private static final int ACTIVITY_REQUEST_CODE_GALLERY = 700;
	private static final int ACTIVITY_REQUEST_VIDEO_CAPTURE= 701;

	// progress dialog
	private ProgressDialog dialog = null;
	private Button file_button = null;
	private Button upload_btn = null;
	private EditText authorText = null;
	private EditText titleText = null;
	private TextView selectedFile = null;
	private FileUploadReceiver receiver = null;
	private FileUploadService serviceBinder = null;
	private IntentFilter filter = null;
	private ComponentName service = null;
	private Boolean isServiceBound = false;


	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.upload);

		this.authorText = (EditText) findViewById(R.id.author_text);
		this.titleText = (EditText) findViewById(R.id.title_text);
		this.selectedFile = (TextView) findViewById(R.id.selected_file);
		this.file_button = (Button) findViewById(R.id.file_select);
        this.file_button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	
            	launchSelectionDialog();
           
            }
        });
        
        this.upload_btn = (Button) findViewById(R.id.upload_btn);
        this.upload_btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                startFileUploadService();
                

            	
            }
        });
        
        // register intent receiver
		this.filter = new IntentFilter( FileUploadService.UPLOAD_COMPLETE );
		this.receiver = new FileUploadReceiver();
		registerReceiver(this.receiver, this.filter);
		
		
	}
	
	private void startGalleryIntent() {
        try {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
           intent.setType("video/*"); 
            startActivityForResult(intent, ACTIVITY_REQUEST_CODE_GALLERY);
        }
        catch (Exception ex) {
            Toast.makeText(this, "No Media Available", 
                Toast.LENGTH_SHORT).show(); 
        }
    }
	
	
	private void startVideoCaptureIntent() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); 
            startActivityForResult(intent, ACTIVITY_REQUEST_VIDEO_CAPTURE);
        }
        catch (Exception ex) {
            Toast.makeText(this, "Recording Not Available", 
                Toast.LENGTH_SHORT).show(); 
        }
    }
	
	private void launchSelectionDialog() {
        try {
        	
        	AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("Video Source Select");
            alertDialog.setMessage("Select one of the sources below");
            alertDialog.setButton("Camcorder", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
            	startVideoCaptureIntent();
                return;

            } }); 

            alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                return;
            }}); 
            
            alertDialog.setButton3("Library", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
            	  startGalleryIntent();
                return;

            }});

            alertDialog.show();


        }
        catch (Exception ex) {

        }
    }
	
	private void launchErrorDialog(int type) {
        try {
        	
        	AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        	switch(type){
        	case 1:
                alertDialog.setTitle("Invalid Author");
                alertDialog.setMessage("You must enter a valid author before uploading");
        		break;
        	case 2:
                alertDialog.setTitle("Invalid Title");
                alertDialog.setMessage("You must enter a valid title before uploading");
        		break;
        	case 3:
                alertDialog.setTitle("Invalid File");
                alertDialog.setMessage("You must select a valid video file before uploading");
        		break;
        	}
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                return;
            } }); 
            alertDialog.show();
        }
        catch (Exception ex) {

        }
    }
	
	   @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data)  {
	        String pathInput = null;
	        switch (requestCode) {
	        	case ACTIVITY_REQUEST_VIDEO_CAPTURE:
	            case ACTIVITY_REQUEST_CODE_GALLERY:
	                if (resultCode == Activity.RESULT_OK) { 
	                    try {
	                        String [] proj = { MediaStore.Video.Media.DATA };  
	                        Cursor cursor = managedQuery(data.getData(), proj, null, null, null);  
	                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA );  
	                        cursor.moveToFirst();  
	                        pathInput = cursor.getString(column_index); 
	                        this.selectedFile.setText(pathInput);
	                        this.selectedFile.setVisibility(View.VISIBLE);
	                    }
	                    catch (Exception ex) {
	                        Toast.makeText(this, "Video not loaded", 
	                                Toast.LENGTH_SHORT).show();
	                        Log.d("StartUploadActivity", ex.getMessage());
	                    }
	                    
	                }
	                else {
	                    return;
	                }
	                break;
	        }
	    }
	
	


	private void showProgressDialog() {
    	
    	this.dialog = ProgressDialog.show( this, "", "Uploading Video.  Please wait...", true);
    }
    private void hideProgressDialog() {
    	
    	
    	this.dialog.cancel();
    	this.authorText.setText("");
    	this.titleText.setText("");
    	this.selectedFile.setText("no file selected");

    	AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    	alertDialog.setTitle("File Upload Complete");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              return;
          } }); 
          alertDialog.show();

    }
    	/*
    private static class uploadVideoTask extends AsyncTask<String, Integer, VmixVideo> {

        @Override
        protected void onPreExecute() {

        }
        
        @Override
        protected VmixVideo doInBackground(String... params) {
            try {

            	return uploadVideo(params[0],params[1],params[2]);
            } catch (Exception e) {
                Log.e("UploadTask", "Error uploading video.", e);
                return null;
            }
            
        }
        
        @Override
        protected void onPostExecute(VmixVideo result) {
            Log.d("UploadTaskComplete", "Downloaded " + result.getMediaId().toString() + " bytes");
        }
 

    }
    
    public void startVideoUpload(String path, String author, String title) {
        this.vUploadVideoTask.execute(path, author, title);
    }
    
    public static VmixVideo uploadVideo(String path, String author, String title) 
    throws SocketTimeoutException, IOException, VmixParseException {
    String BOUNDARY = "------------------219731164328969462735";
    String lineEnd = "\r\n"; 
    String twoHyphens = "--";
    int maxBufferSize = 8192;
    
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    File file = new File(path);
    FileInputStream fileInputStream = new FileInputStream(file);
    
    HttpURLConnection conn = vHttpApi.createHttpURLConnectionPost(new URL(UPLOAD_URL), BOUNDARY);
    
    DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); 
    dos.writeBytes(twoHyphens + BOUNDARY + lineEnd); 
    dos.writeBytes("Content-Disposition: form-data; name=\"video,3gp\";filename=\"" + "video.3gp" +"\"" + lineEnd); 
    dos.writeBytes("Content-Type: " + "	video/3gp" + lineEnd);
    dos.writeBytes(lineEnd); 
    
    int bytesAvailable = fileInputStream.available(); 
    int bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    byte[] buffer = new byte[bufferSize]; 
    
    int bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    int totalBytesRead = bytesRead;
    while (bytesRead > 0) {
        dos.write(buffer, 0, bufferSize); 
        bytesAvailable = fileInputStream.available(); 
        bufferSize = Math.min(bytesAvailable, maxBufferSize); 
        bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
        totalBytesRead = totalBytesRead  + bytesRead;
    }
    dos.writeBytes(lineEnd); 
    dos.writeBytes(twoHyphens + BOUNDARY + twoHyphens + lineEnd); 
    
    fileInputStream.close(); 
    dos.flush(); 
    dos.close(); 
    
    VmixVideo uploadedVideo = new VmixVideo();
	InputStream inputStream = conn.getInputStream();
	// let's make sure that we handle the UTF8 properly
	InputSource inputSource = new InputSource(new InputStreamReader(inputStream, "UTF-8"));
	try {
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document dom = builder.parse( inputSource );
		Element root = dom.getDocumentElement();
		NodeList items = root.getElementsByTagName("media_id"); 
		for( int i = 0; i < items.getLength(); i++ ) {
			// get media item
			Node mediaItem = items.item(i);
			NodeList properties = mediaItem.getChildNodes();
		
			// get a list of the childnodes
			for( int j = 0; j < properties.getLength(); j++ ) {
				Node property = properties.item(j);
				String propertyName = property.getNodeName();

				// valiate that the first child actually exist, if not we hve no value ?
				Node firstChild = property.getFirstChild();
				if( firstChild == null ) {
					continue;
				}
			
			// set id
				if( propertyName.equalsIgnoreCase("id") ) {
					uploadedVideo.setMediaId((String)firstChild.getNodeValue());
				}
		}
		
	}	
	}catch(Exception e){
		
	}
    
    try {
        return uploadedVideo;
    } finally {
    	inputStream.close();
    }
}
	
	
	*/
	   private void startFileUploadService() {

		   int type = ( this.selectedFile.getText().toString().equals((String) "no file selected"))? 3 : 
		   (this.authorText.getText().toString().length() == 0 )? 1 : 
		   (this.titleText.getText().toString().length() == 0)? 2 : 0;

		   if(type == 0){
			   showProgressDialog();
	    	// create intent for the service
	    	Intent intent = new Intent( this, FileUploadService.class); 
	    	intent.putExtra("filePath", this.selectedFile.getText().toString());
	    	intent.putExtra("author", this.authorText.getText().toString());
	    	intent.putExtra("title", this.titleText.getText().toString());
	    	// start service
	    	
	    	startService( intent );
	    	
	    	// need to bind the service as well
	    	Intent bindIntent = new Intent( UploadActivity.this, FileUploadService.class);
	    	// bind service
	    	getApplicationContext().bindService( bindIntent, serviceConnection, Context.BIND_AUTO_CREATE );
	    	this.isServiceBound = true;
		   }else{
			   launchErrorDialog(type);
		   }
		   
	    }
	   

	   
	    private class FileUploadReceiver extends BroadcastReceiver {

			@Override
			public void onReceive(Context arg0, Intent arg1) {

				hideProgressDialog();
				
				
			}
	    	
	    }
	    private ServiceConnection serviceConnection = new ServiceConnection() {
			
			@Override
			public void onServiceDisconnected(ComponentName className) {
				serviceBinder = null;
			}
			
			@Override
			public void onServiceConnected(ComponentName className, IBinder service) {
				
				serviceBinder = (( FileUploadService.FileUploadBinder) service).getService();
			
			}
		};
		
		
		 @Override
		    public void onDestroy() {
		    	
		    	// call parent destroy
		    	super.onDestroy();
		    	// unregister receiver
		    	unregisterReceiver( this.receiver );
		    	
		    	// stop service
		    	this.stopFileUploadService();

		    }
		 
		    private void stopFileUploadService() {
		    	
		    	// unbind
		    	if(this.isServiceBound){
		    		getApplicationContext().unbindService( this.serviceConnection );
		    		this.isServiceBound = false;
		    	}
		    	
		    	stopService( new Intent( this, FileUploadService.class) );
		    	
		    }
	   
}
